package kr.co.happenstance;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import kr.co.happenstance.adapter.AcceptAdapter;
import kr.co.happenstance.lib.MatchingLib;
import kr.co.happenstance.lib.vo.AcceptInfo;
import kr.co.happenstance.lib.vo.LibResultVo;
import kr.co.happenstance.lib.vo.RecipientAcceptListResultVo;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

public class RecipientListActivity extends BaseActivity implements View.OnClickListener, OnItemClickListener{
	protected final String TAG = "<<<RecipientListActivity>>>";
	
	private int matchingRequestSeq;
	
	private String recipientId;
	
	private Handler timerHadler;
	
	/**
	 * 대기시간 종료 시간
	 */
	private Calendar waitingFinishDate;	
	
	private TextView tvCurrentTime;	
	
	/**
	 * ListView Adapter 객체
	 */
	private AcceptAdapter acceptAdapter; 	
	
	/**
	 * Adapter ArrayList객체
	 */
	private ArrayList<AcceptInfo> acceptList;	
	
	/**
	 * ListView 객체
	 */
	private ListView lvAcceptList;
	
	private boolean isLoadingTask;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_recipient_list);
		init(this, C.MENU_ID_RECIPIENT_LIST);
		
		matchingRequestSeq = getIntent().getIntExtra("matchingRequestSeq", -1);
		long waitingFinishDateTimeInMillis = getIntent().getLongExtra("waitingFinishDateTimeInMillis", -1);
		
		waitingFinishDate = Calendar.getInstance();
		waitingFinishDate.setTimeInMillis(waitingFinishDateTimeInMillis);
		
		tvCurrentTime = (TextView) this.findViewById(R.id.tv_current_time);
		tvCurrentTime.setText(new SimpleDateFormat("a hh:mm", Locale.ENGLISH).format(new Date()));

		acceptList = new ArrayList<AcceptInfo>();
		acceptAdapter = new AcceptAdapter(this, acceptList);
		
		lvAcceptList = (ListView) this.findViewById(R.id.lv_accept_list);
		lvAcceptList.setAdapter(acceptAdapter);
		lvAcceptList.setOnItemClickListener(this);
		
		timerHadler = new TimerHandler(this);
		timerHadler.sendEmptyMessage(0);
		
		setAcceptList();
	}	
	
	@Override
	protected void onPause(){
		super.onPause();
		if(timerHadler != null){
			timerHadler.removeMessages(0);
		}	
	}
	
	@Override
	protected void onResume(){
		super.onResume();
		if(timerHadler != null){
			timerHadler.sendEmptyMessage(0);
		}
	}	
	
	@Override
	public void onClick(View view) {
		switch(view.getId()){
			case R.id.btn_reload:
				Log.d(TAG, "btn_reload onClick()................");
				setAcceptList();
				break;	
		}
	}
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id){
		Log.d(TAG, "onItemClick postion["+position+"]");
		if(!isLoadingTask){
			isLoadingTask = true;
			recipientId = this.acceptList.get(position).recipientId;
			new MatchingAcceptTask().execute();
		}
		
	}		
	
	/**
	 * 수신자 동의 리스트 셋팅 메소드
	 */
	private void setAcceptList(){
		new AcceptListTask().execute();
	}
	
	/**
	 * 수신자 동의 리스트 불러오는 Task 클래스
	 * 
	 * @author Administrator
	 *
	 */
	private class AcceptListTask extends AsyncTask<Void, Void, LibResultVo> {
		@Override
		protected void onPreExecute() {
			showProgress();
		}	
		
		@Override
		protected LibResultVo doInBackground(Void... arg0) {
			LibResultVo vo = null;
			try{
				
				MatchingLib lib = new MatchingLib();
				vo = lib.recipientAcceptList(matchingRequestSeq, Double.toString(myLocation.getLatitude()), Double.toString(myLocation.getLongitude()));
				
			}catch(Exception e){
				e.printStackTrace();
			}
			return vo;	
		}
		
		@Override
		protected void onPostExecute(LibResultVo resultVo) {
			closeProgress();
			RecipientAcceptListResultVo vo = (RecipientAcceptListResultVo) resultVo;
			if(vo != null && vo.getResult().equals(C.API_RESULT_VALUE_SUCCESS)){
				if(vo.getAcceptList() != null && vo.getAcceptList().size() > 0){
					
					ArrayList<AcceptInfo> tmpAcceptList = vo.getAcceptList();
					acceptList.clear();
					for(AcceptInfo v: tmpAcceptList){
						acceptList.add(v);
					}
					acceptAdapter.notifyDataSetChanged();
				}				
			}
		}	
		
	}
	
	/**
	 * 매칭 동의(매칭성공) Task 클래스
	 * 
	 * @author Administrator
	 *
	 */
	private class MatchingAcceptTask extends AsyncTask<Void, Void, LibResultVo> {
		@Override
		protected void onPreExecute() {
			showProgress();
		}
		
		@Override
		protected LibResultVo doInBackground(Void... params) {
			LibResultVo result = null;
			try{
				result = new MatchingLib().matchingUpdate(recipientId, matchingRequestSeq, C.MATCH_UPDATE_GBN_MATCHING_ACCEPT);
			}catch(Exception e){
				e.printStackTrace();
			}
			return result;
		}
		
		@Override
		protected void onPostExecute(LibResultVo resultVo) {
			closeProgress();
			
			if(resultVo == null || resultVo.getResult().equals(C.API_RESULT_VALUE_FAIL)){
				Log.d(TAG, "LibResultVo null......");
				new CustomAlertDialogBuilder(RecipientListActivity.this, R.string.alert_title, R.string.alert_msg_exception).create();
			}else{
				Log.d(TAG, "Matching Accept Success..........................");
				
				Intent intent = new Intent();
				intent.putExtra("recipientId", recipientId);
				setResult(RESULT_OK, intent);
				RecipientListActivity.this.finish();
				
			}	
			isLoadingTask = false;
			
		}	
		
	}	
	
	/**
	 * 현재시간과 대기시간 출력 Handler 클래스
	 * 
	 * @author Administrator
	 *
	 */
	private static class TimerHandler extends Handler{
		SimpleDateFormat formatter = new SimpleDateFormat("a hh:mm", Locale.ENGLISH);
		RecipientListActivity activity;
		boolean finish;
		public TimerHandler(RecipientListActivity activity){
			this.activity = activity;
		}
		
		public void handleMessage(Message msg){
			activity.tvCurrentTime.setText(formatter.format(new Date()));	
			
			
			if(activity.waitingFinishDate.getTimeInMillis() - Calendar.getInstance().getTimeInMillis() < 0  && !finish){
				//대기시간 초과시
				finish = true;
				this.removeMessages(0);
				
				//그냥현재 Activity를 종료해줌
				Intent intent = new Intent();
				activity.setResult(RESULT_CANCELED, intent);
				activity.finish();				
				
			}else{	
				this.sendEmptyMessageDelayed(0,1000);
			}
		}		
	}



}
